package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.admin.mapper.AdUserMapper;
import com.itheima.admin.pojo.AdUser;
import com.itheima.admin.service.AdUserService;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * 登录校验
     *
     * @param paramMap
     * @return
     */
    @Override
    public Map<String, Object> loginCheck(Map<String, String> paramMap) {
        //1. 获取参数
        String username = paramMap.get("name");
        String password = paramMap.get("password");
        //2. 参数校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new LeadNewsException("用户名或密码不能为空");
        }
        //3. 通过用户名查询用户信息
        //用户名必须唯一
        AdUser adUserInDB = query().eq("name", username).one();
        //4. 如果用户不存在。报错
        if (null == adUserInDB){
            throw new LeadNewsException("用户名或密码不正确");
        }
        //5. 用户存在，
        //5.1 把前端的密码加盐加密
        String salt = adUserInDB.getSalt();
        password += salt;
        String encryptedPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        //5.2 再与数据库的密码作比较
        if (!encryptedPwd.equals(adUserInDB.getPassword())){
            //5.3 如果不相同，报错
            throw new LeadNewsException("用户名或密码不正确");
        }
        //5.4 相同则构建前端需要的数据格式
        //生成token
        String token = AppJwtUtil.createToken(adUserInDB.getId());
        adUserInDB.setPassword(null);
        adUserInDB.setSalt(null);
        /**
         * {
         *    ...
         *    data:{
         *        token: 生成jwt token
         *        user:{登录用户的信息}
         *    }
         * }
         */
        Map<String, Object> resultMap = new HashMap<String,Object>();
        resultMap.put("token", token);
        resultMap.put("user", adUserInDB);
        return resultMap;
    }
}
